package com.mmall.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * Created by chenxu on 17/7/28.
 */
public class FtpUtil {


    // logger
    // ftpip, ftpuser, ftppass
    // construct
    // public uploadFile(list)
    //

    static Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
    private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
    private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");

    private static FTPClient ftpClient = null;

    private FtpUtil(String ftpIp, String ftpUser, String ftpPass){
        this.ftpIp = ftpIp;
        this.ftpUser = ftpUser;
        this.ftpPass = ftpPass;
    }

    public static boolean uploadFile(List<File> fileList) throws IOException {
        FtpUtil ftpUtil =new FtpUtil(ftpIp, ftpUser,ftpPass);
        boolean result = ftpUtil.uploadFile("img", fileList);
        return result;
    }

    private static boolean uploadFile(String remotePath, List<File> fileList) throws IOException {
        boolean uploaded = true;
        FileInputStream fis =null;

        if (connectServer(ftpIp, ftpUser,ftpPass)){
            try {
                ftpClient.changeWorkingDirectory(remotePath);
                ftpClient.setBufferSize(1024);
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode();
                for(File fileItem: fileList){
                    fis = new FileInputStream((fileItem));
                    ftpClient.storeFile(fileItem.getName(),fis);
                }
            } catch (IOException e) {
                logger.error("",e);
                uploaded = false;
            }finally {
                    fis.close();
                    ftpClient.disconnect();
            }
        }
        return uploaded;
    }

    private static boolean connectServer(String ip, String user, String pass){
        boolean isSuccess = false;
        ftpClient = new FTPClient();
        try {
            ftpClient.connect(ip);
            isSuccess = ftpClient.login(user, pass);
        } catch (IOException e) {
            logger.error("连接ftp服务器失败",e);
        }
        return isSuccess;
    }
}